package com.device.service;

import com.device.dto.ModbusConfigDTO;
import com.device.dto.SubDeviceDTO;
import com.device.entity.SubDevice;
import com.device.repository.SubDeviceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 分设备服务
 */
@Service
public class SubDeviceService {
    
    private static final Logger log = LoggerFactory.getLogger(SubDeviceService.class);
    
    @Autowired
    private SubDeviceRepository subDeviceRepository;
    
    @Autowired
    private DeviceKeyService deviceKeyService;
    
    /**
     * 根据主设备IMEI获取分设备列表
     */
    public List<SubDevice> getSubDevicesByMainImei(String mainDeviceImei) {
        log.info("根据主设备IMEI获取分设备列表，IMEI: {}", mainDeviceImei);
        List<SubDevice> subDevices = subDeviceRepository.findByMainDeviceImeiOrderByCreatedTimeDesc(mainDeviceImei);
        log.info("主设备 {} 下的分设备数量: {}", mainDeviceImei, subDevices.size());
        return subDevices;
    }
    
    /**
     * 根据主设备IMEI获取分设备DTO列表（包含Modbus配置）
     */
    public List<SubDeviceDTO> getSubDeviceDTOsByMainImei(String mainDeviceImei) {
        log.info("根据主设备IMEI获取分设备DTO列表（包含Modbus配置），IMEI: {}", mainDeviceImei);
        List<SubDevice> subDevices = subDeviceRepository.findByMainDeviceImeiOrderByCreatedTimeDesc(mainDeviceImei);
        log.info("主设备 {} 下的分设备数量: {}", mainDeviceImei, subDevices.size());
        
        if (subDevices.isEmpty()) {
            log.info("主设备 {} 下没有分设备", mainDeviceImei);
            return new ArrayList<>();
        }
        
        List<SubDeviceDTO> result = subDevices.stream()
                .map(this::convertToSubDeviceDTO)
                .collect(Collectors.toList());
        
        log.info("主设备 {} 下的分设备DTO数量: {}", mainDeviceImei, result.size());
        return result;
    }

    /**
     * 将SubDevice实体转换为SubDeviceDTO，并加载Modbus配置
     */
    private SubDeviceDTO convertToSubDeviceDTO(SubDevice subDevice) {
        log.info("将SubDevice实体转换为SubDeviceDTO，分设备ID: {}, 分设备编号: {}", subDevice.getId(), subDevice.getSubDeviceId());
        SubDeviceDTO subDeviceDTO = new SubDeviceDTO();
        BeanUtils.copyProperties(subDevice, subDeviceDTO);//将subDevice属性复制给subDeviceDTO
        
        try {
            // 获取Modbus配置列表
            log.info("开始获取分设备 {} 的Modbus配置列表", subDevice.getId());
            List<ModbusConfigDTO> modbusConfigs = deviceKeyService.getModbusConfigsBySubDeviceId(subDevice.getId());
            log.info("分设备 {} 的Modbus配置数量: {}", subDevice.getId(), modbusConfigs.size());
            subDeviceDTO.setModbusConfigs(modbusConfigs);
        } catch (Exception e) {
            log.error("获取分设备 {} 的Modbus配置列表时发生错误: {}", subDevice.getId(), e.getMessage(), e);
            subDeviceDTO.setModbusConfigs(new ArrayList<>());
        }
        
        return subDeviceDTO;
    }
    
    /**
     * 根据ID获取分设备
     */
    public SubDevice getSubDeviceById(UUID id) {
        return subDeviceRepository.findById(id).orElse(null);
    }
    
    /**
     * 根据ID获取分设备DTO（包含Modbus配置）
     */
    public SubDeviceDTO getSubDeviceDTOById(UUID id) {
        return subDeviceRepository.findById(id)
                .map(this::convertToSubDeviceDTO)
                .orElse(null);
    }
    
    /**
     * 根据分设备ID获取分设备
     */
    public SubDeviceDTO getSubDeviceBySubDeviceId(String subDeviceId) {
        SubDevice subDevice = subDeviceRepository.findBySubDeviceId(subDeviceId);
        return subDevice != null ? convertToSubDeviceDTO(subDevice) : null;
    }
    
    /**
     * 创建分设备
     */
    @Transactional
    public SubDevice createSubDevice(SubDevice subDevice) {
        // 检查分设备ID是否已存在
        if (subDeviceRepository.existsBySubDeviceId(subDevice.getSubDeviceId())) {
            throw new RuntimeException("分设备ID已存在");
        }
        
        // 确保ID不为空
        if (subDevice.getId() == null) {
            subDevice.setId(UUID.randomUUID());
        }
        subDevice.setCreatedTime(System.currentTimeMillis());
        subDevice.setUpdatedTime(System.currentTimeMillis());
        
        return subDeviceRepository.save(subDevice);
    }
    
    /**
     * 更新分设备
     */
    @Transactional
    public SubDevice updateSubDevice(UUID id, SubDevice subDevice) {
        SubDevice existingSubDevice = subDeviceRepository.findById(id).orElse(null);
        if (existingSubDevice == null) {
            throw new RuntimeException("分设备不存在");
        }
        
        // 如果分设备ID发生变化，检查新ID是否已存在
        if (!existingSubDevice.getSubDeviceId().equals(subDevice.getSubDeviceId())) {
            if (subDeviceRepository.existsBySubDeviceId(subDevice.getSubDeviceId())) {
                throw new RuntimeException("分设备ID已存在");
            }
        }
        
        subDevice.setId(id);
        subDevice.setCreatedTime(existingSubDevice.getCreatedTime());
        subDevice.setUpdatedTime(System.currentTimeMillis());
        return subDeviceRepository.save(subDevice);
    }
    
    /**
     * 删除分设备（同时删除相关的Key表单）
     */
    @Transactional
    public void deleteSubDevice(UUID id) {
        SubDevice subDevice = subDeviceRepository.findById(id).orElse(null);
        if (subDevice == null) {
            throw new RuntimeException("分设备不存在");
        }
        
        // 删除相关的Key表单
        deviceKeyService.deleteKeysBySubDeviceId(id);
        
        // 删除分设备
        subDeviceRepository.deleteById(id);
    }
    
    /**
     * 批量删除分设备
     */
    @Transactional
    public void deleteSubDevices(List<UUID> ids) {
        for (UUID id : ids) {
            deleteSubDevice(id);
        }
    }
    
    /**
     * 检查分设备ID是否存在
     */
    public boolean existsBySubDeviceId(String subDeviceId) {
        return subDeviceRepository.existsBySubDeviceId(subDeviceId);
    }
    
    /**
     * 获取所有分设备
     */
    public List<SubDevice> getAllSubDevices() {
        return subDeviceRepository.findAll();
    }
}